<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j component-order-item">
    <view class="order-time-status">
      <view class="time">
        <text class="title">
          下单时间：
        </text>
        <text class="text">
          {{ orderInfo.createTime }}
        </text>
      </view>
      <view class="status">
        {{ ['', '待付款', '待发货', '待收货', '', '交易成功', '交易失败', '待成团'][orderInfo.status] }}
      </view>
    </view>
    <view class="order-number">
      <view class="title">
        订单编号：
      </view>
      <view class="text">
        {{ orderInfo.orderNumber }}
      </view>
      <view
        class="copy"
        @tap="copy"
      >
        复制
      </view>
    </view>
    <view class="line" />
    <view class="prod-box">
      <view
        v-for="(prodItem, index) in orderInfo.orderItems"
        :key="index"
        class="prod-item"
      >
        <view class="prod-common">
          <view class="prod-img-image">
            <img-show :src="prodItem.pic" />
          </view>
          <view class="prod-info">
            <view class="prod-name-price">
              <view class="name">
                {{ prodItem.prodName }}
              </view>
              <view class="price">
                ￥<text class="price-big">
                  {{ parsePrice(prodItem.price)[0] }}
                </text>{{ '.' + parsePrice(prodItem.price)[1] }}
              </view>
            </view>
            <view class="prod-sku">
              <view
                v-if="prodItem.skuName"
                class="sku-name"
              >
                {{ prodItem.skuName }}
              </view>
              <view class="total">
                ×{{ prodItem.prodCount }}
              </view>
              <view
                v-if="orderInfo.status === 1"
                class="btn"
                @tap="editAmount(index)"
              >
                修改金额
              </view>
            </view>
            <view class="prod-stutus">
              <view
                v-if="orderInfo.orderType !== 0"
                class="prod-type-item"
              >
                {{ ['', '团购', '秒杀'][orderInfo.orderType] }}
              </view>
              <view
                v-if="orderInfo.orderMold === 1"
                class="prod-type-item"
              >
                虚拟
              </view>
              <view
                v-if="prodItem.platformInterventionStatus && prodItem.platformInterventionStatus!==-1"
                class="prod-stutus-item"
              >
                <!-- 平台介入状态 -1.没有介入 1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功 -->
                {{
                  [
                    "",
                    '平台介入中',
                    '平台介入中',
                    '退款关闭',
                    '',
                    '退款成功'
                  ][prodItem.platformInterventionStatus]
                }}
              </view>
              <view
                v-else-if="prodItem.returnMoneySts && prodItem.returnMoneySts > 0"
                class="prod-stutus-item"
              >
                {{ orderStatus[prodItem.returnMoneySts + ''] }}
              </view>
              <view
                v-if="orderInfo.dvyType === 2 || orderInfo.dvyType === 4"
                class="prod-stutus-item"
              >
                {{ orderInfo.dvyType === 2 ? "自提" : "同城配送" }}
              </view>
              <view
                v-if="!!prodItem.preSellTime"
                class="rep-sell-timer"
                style="display: inline-block;"
              >
                <view
                  v-if="true"
                  class="prod-type-item"
                >
                  预售
                </view>
                <text class="time-txt">
                  预计{{ preSellTimeShowHandler(prodItem.preSellTime) }}发货
                </text>
              </view>
            </view>
          </view>
        </view>
        <!-- 赠品 -->
        <view
          v-for="giftItem in prodItem.giveawayList"
          :key="giftItem.orderItemId"
          class="prod-gift"
        >
          <text class="name">
            【赠品】{{ giftItem.prodName }} {{ giftItem.skuName }}
          </text>
          <text>×{{ giftItem.prodCount }}</text>
        </view>
      </view>
    </view>
    <view class="line bottom" />
    <view class="footer">
      <text class="footer-text">
        共{{ orderInfo.productNums }}件，实收：<text v-if="orderInfo.actualTotal">
          ￥
        </text>
        <text
          v-if="orderInfo.actualTotal"
          class="price"
        >
          {{ orderInfo.actualTotal }}
        </text>
        <text
          v-if="orderInfo.actualTotal && orderInfo.score"
          :decode="true"
          class="price plus"
        >
          +
        </text>
        <text
          v-if="orderInfo.score"
          class="price"
        >
          {{ orderInfo.score }} 积分
        </text>
      </text>
      <view class="footer-btn">
        <view
          v-if="isAuthorities('order:get:info')"
          class="btn-default"
          @tap="orderDetail"
        >
          查看详情
        </view>
        <view
          v-if="isAuthorities('order:virtual:update') && (orderInfo.orderMold == 1 && (orderInfo.status === 3 || orderInfo.status === 5) && (!orderInfo.refundStatus || orderInfo.refundStatus > 2) && orderInfo.writeOffCodes && orderInfo.writeOffCodes.length > 0)"
          class="btn-default btn-primary btn"
          @tap="pickUpGoods()"
        >
          核销
        </view>
        <view
          v-if="isAuthorities('admin:station:orderItemsDelivery') && (orderInfo.status === 2 && orderInfo.dvyType === 2)"
          class="btn-default btn-primary btn"
          @tap="pickUpGoods()"
        >
          提货
        </view>
        <view
          v-if="isAuthorities('order:delivery:update') && (orderInfo.status === 3 && (!orderInfo.refundStatus || orderInfo.refundStatus > 2) &&
            orderInfo.isOnlineDelivery === 0)"
          class="btn-default btn-primary"
          @tap="editLogistics(orderInfo.orderNumber)"
        >
          修改物流
        </view>
        <view
          v-if="isAuthorities('order:delivery:orderItemsDelivery') && (orderInfo.status === 2 && orderInfo.dvyType !== 2 && orderInfo.orderMold !== 1)"
          class="btn-default btn-primary"
          @tap="toShipping"
        >
          去发货
        </view>
      </view>
    </view>
    <!-- 提货或核销弹窗 -->
    <uni-popup
      ref="pickUpPopupRef"
      background-color="#fff"
      :is-mask-click="false"
      class="pop-mask"
    >
      <view class="popup">
        <view class="title-box">
          <text class="title">
            {{ orderInfo.orderMold === 1 ? '订单核销' : '订单提货' }}
          </text>
          <view
            class="close"
            @tap="pickUpClose"
          />
        </view>
        <view class="input-con">
          <input
            v-model="writeOffCode"
            class="input"
            type="text"
            :placeholder="orderInfo.orderMold === 1 ? '请输入核销码核销' : '请输入提货码提货'"
            placeholder-class="placeholder-class"
          >
        </view>
        <view
          class="btn"
          @tap="codeClick"
        >
          {{ orderInfo.orderMold === 1 ? '核销' : '提货' }}
        </view>
        <view class="footer">
          {{ orderInfo.orderMold === 1 ? '不输入核销码，默认为无需校验，直接核销' : '不输入提货码，默认为无需校验，直接提货' }}
        </view>
      </view>
    </uni-popup>
    <!-- 修改金额弹窗 -->
    <uni-popup
      ref="AmountPopupRef"
      background-color="#fff"
      :is-mask-click="false"
      class="pop-mask"
    >
      <view class="popup">
        <view class="title-box">
          <text class="title">
            订单改价
          </text>
          <view
            class="close"
            @tap="amountClose"
          />
        </view>
        <view class="input-con">
          <view class="input-left">
            用户支付金额：
          </view>
          <input
            v-model="actualTotal"
            class="input"
            type="number"
            :placeholder="`当前${orderInfo.orderItems[i].actualTotal}元`"
            placeholder-class="placeholder-class"
            :disabled="orderInfo.orderItems[i].actualTotal < 0.01 && orderInfo.orderItems[i].useScore > 0"
            @blur="changeAmountPopup(chageAmount, 'chageAmount')"
          >
        </view>
        <view class="input-con amount-input-con">
          <view class="input-left">
            运费金额：
          </view>
          <input
            v-model="freightAmount"
            class="input"
            type="number"
            :placeholder="`请输入运费金额，当前${orderInfo.freightAmount}元`"
            placeholder-class="placeholder-class"
            :disabled="orderInfo.orderMold === 1 || orderInfo.dvyType === 2 || orderInfo.platformFreeFreightAmount"
            :placeholder-style="orderInfo.orderMold === 1 || orderInfo.dvyType === 2 ? 'color:#dcdde1' : ''"
            @blur="changeAmountPopup(freightAmount, 'freightAmount')"
          >
        </view>
        <view
          class="btn"
          @tap="amountClick"
        >
          确认
        </view>
        <view class="footer amount-footer">
          修改订单金额会减少用户支付的金额，请谨慎更改
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import util from '@/utils/util'
import Big from 'big.js'
const { isAuthorities } = util

const emit = defineEmits(['refresh', 'updata:orderInfo'])
const props = defineProps({
  orderInfo: {
    type: Object,
    default () {
      return {}
    }
  }
})

const Data = reactive({
  writeOffCode: '', // 核销码
  chageAmount: null, // 减少订单金额
  freightAmount: null, // 运费
  actualTotal: null, // 实际支付
  dataList: [], // 修改金额参数
  i: 0, // 修改金额的当前索引
  dataForm: {}, // 提货数据
  orderStatus: { 1: '买家申请', 2: '卖家接受', 3: '买家发货', 4: '卖家收货', 5: '退款成功', 6: '买家撤回申请', 7: '商家拒绝', '-1': '退款关闭' },
  isSubmit: false
})

const { writeOffCode, chageAmount, freightAmount, i, orderStatus, actualTotal } = toRefs(Data)

const orderDetail = () => {
  uni.navigateTo({
    url: `/package-order/pages/order-detail/order-detail?orderNumber=${props.orderInfo.orderNumber}`
  })
}

const toShipping = () => {
  uni.removeStorageSync('bbcSelectedDelivery')
  uni.navigateTo({
    url: `/package-order/pages/order-shipping/order-shipping?orderNumber=${props.orderInfo.orderNumber}`
  })
}

// 复制文本
const copy = () => {
  util.uniCopy({
    content: props.orderInfo.orderNumber,
    success: (res) => {
      uni.showToast({
        title: res,
        icon: 'none'
      })
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: 'none',
        duration: 3000
      })
    }
  })
}

const pickUpPopupRef = ref()
// 打开提货或核销弹窗
const pickUpGoods = () => {
  pickUpPopupRef.value.open()
  if (props.orderInfo.orderMold !== 1) {
    // 提货数据
    http.request({
      url: '/admin/station/getOrderItemAndStationInfo',
      method: 'get',
      data: {
        orderNumber: props.orderInfo.orderNumber
      }
    }).then(({ data }) => {
      Data.dataForm = data
    })
  }
}

// 关闭提货或核销弹窗
const pickUpClose = () => {
  pickUpPopupRef.value.close()
}

const changeAmountPopup = (value, type) => {
  if (!value) {
    value = '0'
  }
  if (value < 0.01 && value && type === 'freightAmount') {
    Data[type] = 0.01
  }
  if (type === 'chageAmount') { // 修改用户支付金额
    if (Data.actualTotal) {
      if (Data.actualTotal < 0) {
        Data.actualTotal = 0
      }
      value = new Big(props.orderInfo.orderItems[Data.i].actualTotal).minus(Data.actualTotal).round(2).toString()
    }
  }
  const re = /([0-9]+\.[0-9]{2})[0-9]*/
  Data[type] = value.replace(re, '$1')
}

// 确认提货或核销
const codeClick = () => {
  Data.writeOffCode = Data.writeOffCode.trim()
  if ((Data.writeOffCode !== Data.dataForm.stationCode && Data.writeOffCode) && props.orderInfo.orderMold !== 1) {
    uni.showToast({
      title: '提货码错误，请输入正确的提货码',
      icon: 'none'
    })
    return
  }
  // 核销
  const params = {
    url: '/admin/station/orderWriteOffByOrderNumber',
    method: 'put',
    data: {
      orderNumber: props.orderInfo.orderNumber,
      writeOffCode: Data.writeOffCode
    }
  }
  // 提货
  if (props.orderInfo.orderMold !== 1) {
    params.url = '/admin/station/changeStatusAndOrderStation'
    params.data = {
      orderNumber: Data.dataForm.orderNumber,
      stationId: Data.dataForm.stationId
    }
  }
  http.request(params).then(() => {
    uni.showToast({
      title: '操作成功',
      icon: 'none',
      success: () => {
        Data.writeOffCode = ''
        pickUpPopupRef.value.close()
        setTimeout(() => {
          emit('refresh')
        }, 500)
      }
    })
  })
}

// 修改物流信息
const editLogistics = (orderNumber) => {
  uni.navigateTo({
    url: `/package-order/pages/modify-logistics/modify-logistics?orderNumber=${orderNumber}`
  })
}

const AmountPopupRef = ref()
// 打开修改金额弹窗
const editAmount = (index) => {
  Data.i = index
  Data.actualTotal = props.orderInfo.orderItems[Data.i].actualTotal
  Data.chageAmount = '0'
  Data.freightAmount = null
  AmountPopupRef.value.open()
}

// 关闭修改金额弹窗
const amountClose = () => {
  Data.isSubmit = false
  AmountPopupRef.value.close()
}

// 确认修改金额
const amountClick = () => {
  if (Data.isSubmit) {
    return
  }
  if (!Data.chageAmount) {
    uni.showToast({
      title: '修改金额不能为空',
      icon: 'none'
    })
    return
  }
  if (Data.freightAmount < 0) {
    uni.showToast({
      title: '输入的金额必须大于0',
      icon: 'none'
    })
    return
  }
  if ((props.orderInfo.orderItems[Data.i].actualTotal - parseFloat(Data.chageAmount)) < 0) {
    uni.showToast({
      title: '订单金额必须大于0',
      icon: 'none'
    })
    return
  }
  Data.isSubmit = true
  Data.dataList = props.orderInfo.orderItems
  Data.dataList[Data.i].chageAmount = Data.chageAmount
  http.request({
    url: '/order/order/changeAmount',
    method: 'put',
    data: {
      orderId: props.orderInfo.orderId,
      orderItems: Data.dataList,
      orderNumber: props.orderInfo.orderNumber,
      freightAmount: Data.freightAmount ? Data.freightAmount : props.orderInfo.freightAmount
    }
  }).then(() => {
    uni.showToast({
      title: '修改金额成功',
      icon: 'none',
      success: () => {
        AmountPopupRef.value.close()
        Data.chageAmount = null
        Data.freightAmount = null
        setTimeout(() => {
          Data.isSubmit = false
          emit('refresh')
        }, 500)
      }
    })
  }).catch(() => {
    Data.isSubmit = false
  })
}

const parsePrice = (price) => {
  if (price.toString().indexOf('.') > -1) {
    return price.toString().split('.')
  }
  return [price]
}
/**
 * 预售时间显示为 ’MM月DD日‘
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  const timerArr = val.slice(0, -8).trim().split('-')
  return timerArr[1] + '月' + timerArr[2] + '日'
}
</script>

<style lang="scss" scoped>
.component-order-item {
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  line-height: 34rpx;
  margin-bottom: 20rpx;

  .price {
    font-size: 24rpx;
    font-weight: bold;
  }

  .price.plus {
    padding: 0 10rpx;
    font-weight: normal;
  }

  .order-time-status {
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;

    .time {
      .title {
        color: #999999;
      }
    }

    .status {
      color: #082ba6;
    }
  }

  .order-number {
    margin-top: 10rpx;
    display: flex;
    align-items: center;
    font-size: 24rpx;
    line-height: 34rpx;

    .title {
      color: #999999;
    }

    .copy {
      margin-left: 10rpx;
      width: 72rpx;
      height: 32rpx;
      background: #ffffff;
      border: 2rpx solid #dddddd;
      opacity: 1;
      text-align: center;
      border-radius: 20rpx;
      font-size: 20rpx;
    }
  }

  .line {
    margin-top: 30rpx;
    margin-bottom: 28rpx;
    border-bottom: 2rpx dashed #dddddd;
  }

  .line.bottom {
    margin-bottom: 30rpx;
  }

  .prod-box {
    display: flex;
    flex-direction: column;

    .prod-item {
      display: flex;
      margin-bottom: 10px;
      flex-direction: column;

      .prod-common {
        display: flex;

        .prod-img-image {
          width: 140rpx;
          height: 140rpx;
          border-radius: 10rpx;
        }

        .prod-info {
          display: flex;
          flex-direction: column;
          margin-left: 16rpx;
          width: 530rpx;

          .prod-name-price {
            display: flex;
            justify-content: space-between;
            line-height: 40rpx;

            .name {
              font-size: 28rpx;
              width: 358rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .price-big {
              font-size: 32rpx;
            }
          }

          .prod-sku {
            display: flex;
            justify-content: space-between;
            font-size: 24rpx;
            color: #999999;
            line-height: 32rpx;
            margin-top: 10rpx;

            .sku-name {
              max-width: 60%;
            }

            .btn {
              display: inline-block;
              font-size: 20rpx;
              color: #082ba6;
            }
          }

          .prod-stutus {
            .prod-stutus-item {
              display: inline-block;
              margin-top: 18rpx;
              margin-right: 10rpx;
              padding: 2rpx 6rpx;
              font-size: 20rpx;
              line-height: 14px;
              background-color: #ECF0FF;
              color: #082ba6;
              // border: 2rpx solid #ECF0FF;
              border-radius: 4rpx;
            }

            .prod-type-item {
              display: inline-block;
              margin-top: 18rpx;
              margin-right: 10rpx;
              line-height: 14px;
              padding: 2rpx 6rpx;
              font-size: 20rpx;
              color: #fff;
              background-color: #082ba6;
              // border: 2rpx solid #082ba6;
              border-radius: 4rpx;
            }
            .rep-sell-timer {
              .time-txt{
                font-size: 20rpx;
                color: #082ba6;
              }
            }
          }
        }

        &:last-child {
          margin-bottom: 0;
        }
      }

      .prod-gift {
        display: flex;
        justify-content: space-between;
        font-size: 24rpx;
        vertical-align: middle;
        box-sizing: border-box;
        margin-left: 140rpx;

        .name {
          max-width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-right: 10rpx;
        }
      }
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .footer-text {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 24rpx;
    }

    .footer-btn {
      display: flex;
      justify-content: flex-end;

      .btn-default {
        display: inline-block;
        font-size: 24rpx;
        padding: 14rpx 28rpx 12rpx;
        border: 2rpx solid #dddddd;
        border-radius: 32rpx;
      }

      .btn-primary {
        border: 2rpx solid #082ba6;
        color: #082ba6;
      }

      .btn-default+.btn-default {
        margin-left: 20rpx;
      }

      .btn {
        text-align: center;
        width: 96rpx;
      }
    }
  }

  .pop-mask {
    .popup {
      width: 590rpx;
      .title-box {
        position: relative;
        height: 138rpx;

        .title {
          position: absolute;
          top: 30rpx;
          left: 50%;
          transform: translate(-50%, 0);
          font-size: 28rpx;
          font-weight: bold;
        }

        .close {
          position: absolute;
          top: 30rpx;
          right: 0;
          transform: translate(-50%, 0);
          width: 36rpx;
          height: 36rpx;
          line-height: 32rpx;
          background-color: #F5F5F5;
          border-radius: 50%;
          font-size: 20rpx;
          text-align: center;
          color: #999999;
        }

        .close::after {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 14rpx;
          height: 14rpx;
          background: url(~@/static/images/close.png) no-repeat;
          background-size: 14rpx 14rpx;
        }
      }

      .input-con {
        margin: auto;
        display: flex;
        align-items: center;
        padding: 0 30rpx;
        height: 64rpx;
        width: 100%;
        border-radius: 4rpx;
        box-sizing: border-box;

        :deep(.placeholder-class) {
          font-size: 28rpx;
        }

        .input {
          background: #F7F8FA;
          height: 64rpx;
          font-size: 24rpx;
          width: 100%;
          padding-left: 20rpx;
        }

        :deep(.placeholder-class) {
          color: #999999;
        }
      }

      .input-left {
        font-size: 28rpx;
        font-weight: 400;
        flex-basis: auto;
        white-space: nowrap;
      }

      .amount-input-con {
        margin-top: 30rpx;
      }

      .btn {
        background: #082BA6;
        margin: 40rpx auto auto;
        width: calc(100% - 60rpx);
        height: 70rpx;
        text-align: center;
        font-size: 26rpx;
        color: #FFFFFF;
        padding: 14rpx 28rpx 12rpx;
        border: 2rpx solid #dddddd;
        border-radius: 70rpx;
        box-sizing: border-box;
      }

      .footer {
        display: flex;
        font-size: 24rpx;
        color: #999999;
        justify-content: center;
        margin: 28rpx 0 60rpx 0;
      }

      .amount-footer {
        margin-top: 20rpx;
      }

      :deep(.modify-logistics) {
        .logistics {
          margin-top: 0;
        }
      }
    }
  }

  ::v-deep(.uni-popup__wrapper) {
    border-radius: 10rpx;
  }
}
</style>
